import 'package:automated_test/common/db_helper.dart';
import 'package:flutter/material.dart';

class SearchBarDelegate extends SearchDelegate {
  @override
  List<Widget>? buildActions(BuildContext context) {
    return [
      IconButton(
        onPressed: () {
          query = "";
          showSuggestions(context);
        },
        icon: Icon(Icons.clear),
      )
    ];
  }

  @override
  Widget? buildLeading(BuildContext context) {
    return IconButton(
      onPressed: () {
        if (query.isEmpty) {
          close(context, null);
        } else {
          query = "";
          showSuggestions(context);
        }
      },
      icon: AnimatedIcon(
        icon: AnimatedIcons.menu_arrow,
        progress: transitionAnimation,
      ),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return Result(query: query);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return Suggestion();
  }
}

class Suggestion extends StatefulWidget {
  @override
  _SuggestionState createState() => _SuggestionState();
}

class _SuggestionState extends State<Suggestion> {
  List<String>? gates;

  Future getGates() =>
      DbHelper.queryGates().then((value) => setState(() => gates = value));

  bool gatesIsEmpty() {
    if (gates == null || gates!.isEmpty) return true;
    return false;
  }

  _buildList() {
    return ListView.builder(
      itemBuilder: (context, index) => ListTile(
        title: Text(gates![index]),
      ),
      itemCount: gates!.length,
    );
  }

  @override
  initState() {
    super.initState();
    getGates();
  }

  @override
  Widget build(BuildContext context) {
    return gatesIsEmpty() ? Container() : _buildList();
  }
}

class Result extends StatefulWidget {
  final String query;

  const Result({Key? key, required this.query}) : super(key: key);

  @override
  _ResultState createState() => _ResultState();
}

class _ResultState extends State<Result> {
  List<String>? gates;

  bool gatesIsEmpty() {
    if (gates == null || gates!.isEmpty) return true;
    return false;
  }

  _buildList() => ListView.builder(
        itemBuilder: (context, index) => ListTile(
          title: Text(gates![index]),
        ),
        itemCount: gates!.length,
      );

  @override
  initState() {
    super.initState();
    DbHelper.fuzzyQueryGate(widget.query)
        .then((value) => setState(() => gates = value));
  }

  @override
  Widget build(BuildContext context) {
    return gatesIsEmpty() ? Container() : _buildList();
  }
}
